
import path from 'path';

let allSeriesCache;

function allSeries() {
  if (allSeriesCache) {
    return Promise.resolve(allSeriesCache);
  }

  return fetch('/aurora/asset/allSeries')
    .then(d => d.json())
    .then(d => {
      allSeriesCache = d;
      return d;
    })
}

/**
 * 获取场景的启动 js 代码文本以及 manifest json object
 * @param {string} sceneName 场景全名称或挂件全名称, `${series}/${scene}` | `${series}/${pendant}`
 * @param {string} jsPath 结尾是 '.js' 的路径
 * @returns {Promise<Array>}
 */
function fetchComponentScript(sceneName, jsPath) {
  let manifestPath;
  manifestPath = jsPath.substring(0, jsPath.length - 3) + "-manifest.json";
  const jsUrl = assetPath(sceneName, jsPath, true);
  const manifestUrl = assetPath(sceneName, manifestPath, true);
  return Promise.all([
    fetch(jsUrl).then(d => d.ok ? d.text() : Promise.reject(`${sceneName} 的 js 文件不存在`)),
    fetch(manifestUrl).then(d => {
      if (d.ok) {
        return d.json();
      }
      console.warn(`${sceneName} 的 manifest 文件不存在`);
      return Promise.resolve(null);
    }),
  ]);
}

let libs = {
  //
};

function requireLibrary(ls) {
  let array = ls.map((libName, index) => {
    if (libs[libName]) {
      return Promise.resolve(libs[libName]);
    }

    return fetch('/lib/' + ls[index] + '.js')
      .then(res => res.text())
      .then((script) => {
        let exports = {};
        //let module = {}; // 这里 module 不写, 是因为如果 webpack 打包, 自带 module
        eval(script);

        libs[ls[index]] = exports;
        return exports;
      })
      .catch(e => {console.error(e);});
  })

  return Promise.all(array);
};

/**
 * 可以这样调用:
 * assetPath(seriesName, path, false)
 * assetPath(sceneFullName, path, true)
 * assetPath(pendantFullName, path, true)
 */
function assetPath(seriesName, _path, isFullName = false) {
  _path = encodeURI(_path);

  if (isFullName) {
    return path.resolve('/aurora-res', seriesName, '..', _path);
  } else {
    return path.resolve('/aurora-res', seriesName, _path);
  }
}

export default {
  allSeries, fetchComponentScript, requireLibrary,
  assetPath
};
